home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / listings / v_03_02 / 3n02011a < prev    next >
Text File  |  1991-12-24  |  2KB  |  59 lines

  1. // challoc.c - implementation of "chunk" memory allocator.
  2.  
  3. #include "challoc.h"
  4. #include <assert.h>
  5. #include <stddef.h>
  6.  
  7. // Don't change without changing operator new
  8. // if/else statements as well!
  9. ChunkRoot   ChunkAllocated::Roots
  10.     [ChunkRoot::NUMBER_OF_BINS] =
  11.     {
  12.     2,      4,      8,      16,
  13.     32,     64,     128,    256,
  14.     512,    1024
  15.     };
  16.  
  17. ChunkRoot::ChunkRoot(size_t ElementSize_)
  18.     : Root(NULL), FreeList(NULL),
  19.       ElementSize(ElementSize_),
  20.       ElementsPerChunk(CHUNK_SIZE/ElementSize_)
  21.     {
  22.     }
  23.  
  24. // ~ChunkRoot - Free linked list of chunks
  25. ChunkRoot::~ChunkRoot()
  26.     {
  27.     ChunkRootLink     *Next, *Current = Root;
  28.     while(Current)
  29.         {
  30.         Next    = Current->Next;
  31.         free((void *)Current);
  32.         Current = Next;
  33.         }
  34.     }
  35.  
  36.  
  37.  
  38. void    ChunkRoot::AddChunk()
  39.     {
  40.     size_t  Size = ElementSize * ElementsPerChunk
  41.             + offsetof(ChunkRootLink, LDAlign);
  42.     ChunkRootLink   *MallocResult = (ChunkRootLink *)
  43.                                 malloc(Size);
  44.     assert(MallocResult != NULL);
  45.     MallocResult->Next    = Root;
  46.     Root            = MallocResult;
  47.  
  48.     char    *BytePointer    = (char *)MallocResult->Chunk();
  49.     for(int i = 1; i < ElementsPerChunk; ++i)
  50.         {
  51.         ((ChunkAllocated *)BytePointer)->Next   =
  52.                     (ChunkAllocated*)(BytePointer+ElementSize);
  53.         BytePointer += ElementSize;
  54.         }
  55.     ((ChunkAllocated *)BytePointer)->Next   = FreeList;
  56.     FreeList    = (ChunkAllocated *)MallocResult->Chunk();
  57.     }
  58.  
  59.